package com.lxx.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class CommandUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(CommandUtils.class);

	
	/**
	 * 执行shell命令, 并获取返回信息
	 * @param cmd
	 * @return
	 */
	public static final List<String> execWithRet(String cmd) {
		Runtime rt = Runtime.getRuntime();
		List<String> lines = new ArrayList<>();
		try {
			Process p = rt.exec(cmd);
			int ret = p.waitFor();
			if (ret == 0) {
				try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))){
					String tmp = null;
					while ((tmp = br.readLine()) != null) {
						tmp = StringUtils.trimToNull(tmp);
						if (tmp != null) {
							lines.add(tmp);
						}
					}
				} catch (Exception e) {
					LOGGER.error("execute command : \"{}\" read info fail", cmd);
				}
			} else {
				LOGGER.error("execute command : \"{}\" fail", cmd);
			}
		} catch (Exception e) {
			LOGGER.error("", e);
			throw new RuntimeException(e);
		}
		return lines;
	}
	
	/**
	 * 执行shell命令, 没有返回信息
	 * @param cmd
	 * @return
	 */
	public static final void exec(String cmd) {
		Runtime rt = Runtime.getRuntime();
		try {
			Process p = rt.exec(cmd);
			int ret = p.waitFor();
		} catch (Exception e) {
			LOGGER.error("", e);
			throw new RuntimeException(e);
		}
	}
	
	public static void main(String[] args) {
		List<String> lines = execWithRet("wmic cpu get name");
		System.out.println(lines.size());
		System.out.println(lines);
	}

}
